package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.pojo.OrderSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service(interfaceClass = OrderSettingService.class)
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    @Transactional
    public void addAll(List<OrderSetting> orderSettings) {
        log.info("[预约设置-批量添加]data:{}", orderSettings);
        for (OrderSetting orderSetting : orderSettings) {
            this.editNumberByDate(orderSetting.getOrderDate(),orderSetting.getNumber());

        }
    }

    @Override
    public List<OrderSetting> findByMonth(Integer month, Integer year) {
        String startDate = String.format("%d-%d-%d", year, month, 1);
        String endDate = String.format("%d-%d-%d", year, month, 31);
        return orderSettingDao.selectByOrderDateRange(startDate,endDate);
    }

    @Override
    @Transactional
    public void editNumberByDate(Date orderDate, int number) {
        log.info("[预约设置-根据日期编辑]data:{},number:{}",orderDate,number);
        //查询历史数据
        OrderSetting po = orderSettingDao.selectByOrderDate(orderDate);
        if (null != po) {
            //存在就更新
            orderSettingDao.updateNumberById(po.getId(), number);
            //否则插入
        } else {
            orderSettingDao.insert(new OrderSetting(orderDate,number));
        }
    }
}
